package com.manager.system.service.impl;
import com.manager.common.dao.SuperDao;
import com.manager.common.utils.DataTools;
import com.manager.common.utils.ObjectUtils;
import com.manager.common.vo.PageVO;
import com.manager.model.Dictionary_Data;
import com.manager.model.System_Permission;
import com.manager.system.service.DictionaryDataService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.query.NativeQuery;
import org.hibernate.transform.Transformers;
import org.hibernate.type.StandardBasicTypes;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@SuppressWarnings("all")
@Component("dictionaryDataServiceImpl")
@Transactional(readOnly = true)
public class DictionaryDataServiceImpl extends SuperDao<Object> implements DictionaryDataService{

	@Override
	@Transactional
	public PageVO getDicMap(Dictionary_Data model) {
		// TODO Auto-generated method stub
		List<Object> params = new ArrayList<Object>();
		StringBuffer sb = new StringBuffer("from Dictionary_Data t where 1 = 1 ");
		if(!StringUtils.isEmpty(model.getGroupName())){
			sb.append(" and concat(concat(t.groupName, t.groupId), t.text) like # ");
			params.add("%"+model.getGroupName()+"%");
		}

		if(StringUtils.isNotEmpty(model.getGroupId())){
			sb.append(" and t.groupId = # ");
			params.add(model.getGroupId());
		}

		if(StringUtils.isNotEmpty(model.getpId())){
			sb.append(" and t.pId = # ");
			params.add(model.getpId());
		}

		String sql = sb.toString();
		sql = ObjectUtils.replaceIndexByList(sql, params);
		
		List<Dictionary_Data> list = this.getList(sql, params.toArray(), model.getStart(), model.getLimit(),  " order by t." + model.getOrderby() + " " + model.getDesc());
		int sum = this.getListCount("select count(*) " + sql, params.toArray(), "");
		int count = (int)Math.ceil(Double.valueOf(sum)/Double.valueOf(model.getLimit()));

		return PageVO.create(model.getStart(),count,list);
	}

	@Override
	@Transactional
	public void insertDic(Dictionary_Data model) {
		// TODO Auto-generated method stub
		this.addT(model);
	}

	@Override
	@Transactional
	public void updateDic(Dictionary_Data model) {
		// TODO Auto-generated method stub
		Dictionary_Data data = (Dictionary_Data) this.loadT(new Dictionary_Data(), model.getId());
		BeanUtils.copyProperties(model, data, new String[]{"id","createTime"});
		this.updateT(data);
	}

	@Override
	@Transactional
	public void deleteDic(Dictionary_Data model) {
		// TODO Auto-generated method stub
		Dictionary_Data data = (Dictionary_Data) this.loadT(new Dictionary_Data(), model.getId());
		model.setGroupId(data.getGroupId());
		this.delete(data);
	}

	@Override
	@Transactional
	public List<Dictionary_Data> getDicType() {
		// TODO Auto-generated method stub
		String sql = "select  GROUP_ID as groupId ,GROUP_NAME as groupName, p_id as pId from tb_dictionary_data GROUP BY  GROUP_ID,GROUP_NAME ";
		NativeQuery query = session.createNativeQuery(sql)
						.addScalar("groupId", StandardBasicTypes.STRING).addScalar("groupName", StandardBasicTypes.STRING)
				        .addScalar("pId", StandardBasicTypes.STRING)
						.setResultTransformer(Transformers.aliasToBean(Dictionary_Data.class));
		List<Dictionary_Data> list = query.list();
		
		if(list == null || list.size() <= 0) {
			return new ArrayList<>();
		}
				
		return list;
	}

	
	@Override
	@Transactional
	public boolean isDataExsit(Dictionary_Data model) {
		List<Object> params = new ArrayList<Object>();

		String hql=" select t from Dictionary_Data t where t.groupId = ?1 and ( t.text = ?2  or t.val = ?3 ) ";
		params.add(model.getGroupId());
		params.add(model.getText());
		params.add(model.getVal());
		if(StringUtils.isNotEmpty(model.getId())){
			hql += " and t.id != ?4 ";
			params.add(model.getId());
		}
		Dictionary_Data ddata=(Dictionary_Data) this.getListOne(hql, params.toArray(), "");
		if(ddata==null) {
			return false;
		}
		return true;
	}

	@Override
	@Transactional
	public void initDictonaryData() {
		ConcurrentMap<String, List<Dictionary_Data>> dictionaryMap = new ConcurrentHashMap<String, List<Dictionary_Data>>();
		String sql = "from Dictionary_Data t ";
		List<Dictionary_Data> list = this.getList(sql, 0, 0, "");
		for(Dictionary_Data data:list){
			String id = data.getGroupId();
			if(dictionaryMap.containsKey(data.getGroupId())){
				dictionaryMap.get(id).add(data);
			}else{
				List<Dictionary_Data> dataList = new ArrayList<Dictionary_Data>();
				dataList.add(data);
				dictionaryMap.put(id, dataList);
			}
		}
		DataTools.allDicList = list == null ? new ArrayList<>() : list;
		DataTools.dictionaryMap = dictionaryMap;
	}


	@Override
	@Transactional
	public Dictionary_Data getDicByGroupIdAndValue(Dictionary_Data model) {
		String hql = " from Dictionary_Data t where t.groupId = ?0 and t.val = ?1 ";
		Dictionary_Data dic = (Dictionary_Data) this.getListOne(hql, new String[] {model.getGroupId(),model.getVal()}, "");
		return dic;
	}

	@Override
	public Dictionary_Data getDicByGroupIdAndText(Dictionary_Data model) {
		String hql = " from Dictionary_Data t where t.groupId = ?0 and t.text = ?1 ";
		Dictionary_Data dic = (Dictionary_Data) this.getListOne(hql, new String[] {model.getGroupId(),model.getText()}, "");
		return dic;
	}

	@Override
	@Transactional
	public List<Dictionary_Data> getAllDicData(String pId) {
		List<Object> params = new ArrayList<>();
		String hql = " from Dictionary_Data t where 1 = 1 ";
		String orderSql = "  ";
		if(StringUtils.isNotEmpty(pId)){
			hql += " and t.pId = ?0 ";
			orderSql = " order by t.orderNum asc ";
			params.add(pId);
		}
		List<Dictionary_Data> list = this.getList(hql, params.toArray() , 0, 0, orderSql);

		return list;
	}

	@Override
	@Transactional
	public List<Dictionary_Data> getDicTreeDataByGroupId(Dictionary_Data model) {
		String sql = " from Dictionary_Data t where t.groupId = ?0 ";
		List<Object> params = new ArrayList<>();

		params.add(model.getGroupId());

		if(StringUtils.isNotEmpty(model.getText())){
			sql += " and t.text like ?1 ";
			params.add("%"+model.getText()+"%");
		}

		List<Dictionary_Data> list = this.getList(sql, params.toArray() , 0, 0, " order by t.orderNum ");
		return list;
	}

	@Override
	public String getDicByGroupIdAndValue(String groupId, String value) {
		String hql = " from Dictionary_Data t where t.groupId = ?0 and t.val = ?1 ";
		Dictionary_Data dic = (Dictionary_Data) this.getListOne(hql, new String[] {groupId,value}, "");
		if(dic == null) {
			return "";
		}
		return dic.getText();
	}

	@Override
	public List<Dictionary_Data> getDataListByDicGroupId(String groupId) {
		String hql = " from Dictionary_Data t where t.groupId = ?0  ";
		List<Dictionary_Data> list = this.getList(hql, new Object[]{groupId}, 0, 0);

		return list;
	}

	@Override
	public List<Dictionary_Data> getChildrenDataByParentId(String parentId) {
		String hql = " from  Dictionary_Data t where t.pId = ?0  ";

		List<Dictionary_Data> list = this.getList(hql, new Object[]{parentId}, 0, 0);

		return list;
	}

	@Override
	public List<Dictionary_Data> getTreeDicData() {
		String hql = " select  case  WHEN p_id = '0' then GROUP_ID  WHEN p_id != '0' then p_id  END AS pId," +
				" text as text, table_id as id , 'data' as temp1 from tb_dictionary_data  order by text   ";

		NativeQuery query2 = this.session.createNativeQuery(hql)
				.addScalar("id", StandardBasicTypes.STRING).addScalar("text", StandardBasicTypes.STRING)
				.addScalar("pId", StandardBasicTypes.STRING).addScalar("temp1", StandardBasicTypes.STRING)
				.setResultTransformer(Transformers.aliasToBean(Dictionary_Data.class));
		List<Dictionary_Data> ALLList = query2.list();

		String sql = "select  GROUP_ID as id ,GROUP_NAME as text, p_id as pId, 'group' as temp1  from tb_dictionary_data where p_id = '0' GROUP BY  GROUP_ID,GROUP_NAME,p_id order by text ";
		NativeQuery query = this.session.createNativeQuery(sql)
				.addScalar("id", StandardBasicTypes.STRING).addScalar("text", StandardBasicTypes.STRING)
				.addScalar("pId", StandardBasicTypes.STRING).addScalar("temp1", StandardBasicTypes.STRING)
				.setResultTransformer(Transformers.aliasToBean(Dictionary_Data.class));
		List<Dictionary_Data> list = query.list();

		if(list == null || list.size() <= 0) {
			return new ArrayList<>();
		}

		ALLList.addAll(list);

		return ALLList;
	}

	@Override
	public List<Dictionary_Data> getDicDataByGroupId(String groupId) {
		String sql = "select t from  Dictionary_Data t where t.groupId = ?1 ";

		List<Dictionary_Data> list = this.getList(sql,new Object[]{groupId},0,0);

		return list;
	}

	@Override
	public JSONArray getProcessItemData(String parentId) {
		String sql = " from  Dictionary_Data t where t.pId  = ?0 ";
		String carafitTypeSQL = " from  Dictionary_Data t where t.groupId = 'crarft_type' ";
		String productionProcessDetailSQL = " from Dictionary_Data t where t.pId in ( select t1.id from  Dictionary_Data t1 where t1.pId  = ?0) ";

		List<Dictionary_Data> list = this.getList(sql,new Object[]{parentId},0,0,"");
		List<Dictionary_Data> carafitTypeList = this.getList(carafitTypeSQL,new Object[]{},0,0,"");
		List<Dictionary_Data> productionProcessDetailList = this.getList(productionProcessDetailSQL,new Object[]{parentId},0,0,"");

		JSONArray jsonArray = JSONArray.fromObject(list);

		for(int i = 0;i < jsonArray.size();i++){
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			String id = jsonObject.getString("id");
			List<Dictionary_Data> temp = new ArrayList<>();
			for(Dictionary_Data dictionary_data: productionProcessDetailList){
				if(id.equals(dictionary_data.getpId())){
					temp.add(dictionary_data);
				}
			}
			jsonObject.put("processItemList",temp);
			jsonObject.put("crarftType",carafitTypeList);
			productionProcessDetailList.removeAll(temp);
		}

		return jsonArray;
	}

	@Override
	public List<Dictionary_Data> getMenuTreeDicData() {
		String sql = " from Dictionary_Data t  ";
		List<Dictionary_Data> list = this.getList(sql,new Object[]{},0,0," order by t.orderNum asc ");
		return list;
	}

	@Override
	public List<Dictionary_Data> getDicTreeData() {
		List<Dictionary_Data> result = new ArrayList<>();
		String sql = " SELECT DISTINCT t.groupId,t.groupName,t.pId from Dictionary_Data t ";
		List<Object[]> list = this.getList(sql,new Object[]{},0,0,"");
		for(Object[] array: list){
			Dictionary_Data dictionary_data = new Dictionary_Data();
			dictionary_data.setGroupId((String)array[0]);
			dictionary_data.setGroupName((String)array[1]);
			dictionary_data.setpId((String)array[2]);
			result.add(dictionary_data);
		}
		return result;
	}
}
